<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      title="销售退货"
      :btnList="fullInfo.btnList"
      :needOperateAffair="true"
      :operateAffairData="affairTableInfo"
    >
      <template v-slot:full-button>
        <el-button
          v-if="
            $permission('saleReturnOrder:update') &&
            infoList.data.status === 'pend_confirm'
          "
          @click="makeSure()"
          >确认</el-button
        >
        <el-button
          v-if="
            $permission('saleReturnOrder:update') &&
            infoList.data.status === 'pend_confirm'
          "
          @click="reject()"
          >拒绝</el-button
        >
        <el-button
          v-if="
            $permission('saleReturnOrder:update') &&
            infoList.data.status === 'pend_receive'
          "
          @click="receive()"
          >收货</el-button
        >
        <el-button
          v-if="
            $permission('saleReturnOrder:update') &&
            infoList.data.status === 'pend_receive'
          "
          @click="refuse()"
          >拒收</el-button
        >
      </template>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <basic-information :info="infoList" />
        </div>
      </div>

      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('detailInfo') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- 表格 -->
          <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
            <page-table
              :refresh="tableInfo.refresh"
              v-model:data="tableInfo.data"
              :api="tableInfo.api"
              :summary="true"
              :pager="false"
              :summaryFieldList="tableInfo.summaryFieldList"
              :checkBox="false"
              :tab-index="true"
              :query="filterInfo.query"
              :field-list="tableInfo.fieldList"
              :handle="tableInfo.handle"
            >
              <template v-slot:col-licenseNumber="scope">
                <p>{{ scope.row.licenseNumber || '-' }}</p>
                <p>{{ scope.row.brandName || '-' }}</p>
              </template>
              <template v-slot:col-commonName="scope">
                <p>{{ scope.row.commonName || '-' }}</p>
                <p>{{ scope.row.productCode || '-' }}</p>
                <p>{{ scope.row.alias || '-' }}</p>
              </template>
              <template v-slot:col-type="scope">
                <p>{{ scope.row.productTypeValue || '-' }}</p>
                <p>{{ scope.row.codeTypeValue || '-' }}</p>
                <p>{{ scope.row.classifyValue || '-' }}</p>
              </template>
              <template v-slot:col-standard="scope">
                <p>{{ scope.row.standard || '-' }}</p>
                <p>{{ scope.row.unitName || '-' }}</p>
              </template>
              <template v-slot:col-qty="scope">
                <span>{{ scope.row.qty.toFixed(2) }}</span>
              </template>
              <template v-slot:col-needDealQty="scope">
                <p>
                  {{
                    (scope.row.deliverPendqty + scope.row.deliverQty).toFixed(2)
                  }}
                </p>
                <p>{{ scope.row.refuseQty.toFixed(2) }}</p>
                <p>{{ scope.row.needDealQty.toFixed(2) }}</p>
              </template>
            </page-table>
          </el-form>
        </div>
      </div>
    </NewFullScreen>
    <IndividualDetails
      v-if="individualInfo.visible"
      v-model:show-dialog="individualInfo.visible"
      :query="individualInfo.query"
      :info="individualInfo.info"
    />
  </div>
</template>

<script setup name="saleOrderDetail">
import PageTable from '@/components/PageTable/index'
import {
  getSaleReturnDetail,
  saleReturnConfirm,
  saleReturnReject,
  saleReturnReceive,
  saleReturnRefuse,
  getSaleReturnRefuseDetailAll,
} from '@/api/supplier.js'
import { detailPurchReturn, getSaleReturnOrderDetailAll } from '@/api/purch'
import BasicInformation from '@/components/BasicInformation/index'
import { orderAffairAll } from '../../../api/affair'
import IndividualDetails from './IndividualDetails'

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const props = defineProps({
  visible: {
    type: Boolean,
  },
  orderId: {
    type: [String, Number],
  },
})

const fullInfo = reactive({
  btnList: [{ type: 'slot', value: 'button' }],
})
const infoList = reactive({
  data: {},
  fieldList: [
    { label: '退货单号', value: 'orderNo' },
    // { label: "采购退货单号", value: "purchReturnNo" },
    { label: '客户', value: 'orgName' },
    { label: '状态', value: 'statusValue' },
    { label: '申请人', value: 'createUserName' },
    { label: '部门', value: 'deptName' },
    { label: '申请时间', value: 'createTime' },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
})
// 过滤相关配置
const filterInfo = reactive({
  query: {
    orderId: props.orderId,
  },
})
// 表格相关
const tableInfo = reactive({
  api: getSaleReturnOrderDetailAll,
  refresh: 1,
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'sumAmt', formatter: proxy.$fn.TripartiteMethod },
  ],
  data: [],
  fieldList: [
    { label: '证号/生产厂家', value: 'licenseNumber', type: 'slot' },
    { label: '通用名称/编码/别名', value: 'commonName', type: 'slot' },
    { label: '产品类型/条码类型/产品分类', value: 'type', type: 'slot' },
    { label: '规格/计量单位', value: 'standard', type: 'slot' },
    { label: '生产批号', value: 'batchNumber' },
    { label: '生产日期', value: 'productionDate' },
    { label: '失效日期', value: 'validityDate' },
    {
      label: '退货量',
      value: 'qty',
      type: 'column',
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      label: '单价',
      value: 'price',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
    { label: '总金额', value: 'sumAmount' },
    { label: '退货原因', value: 'reason' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '80',
    btList: [
      {
        label: '个体详情',
        event: individualDetails,
        show: true,
      },
    ],
  },
})
const affairTableInfo = reactive({
  api: orderAffairAll,
  query: {
    orderType: 1,
    orderId: props.orderId,
    sort: 'operate_time desc',
  },
})
const individualInfo = reactive({
  visible: false,
  query: {},
  info: {},
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})
watch(
  () => tableInfo.data,
  (val) => {
    if (val.length) {
      tableInfo.mergeData = proxy.$fn.getMergeData(val)
    }
  }
)
onMounted(() => {
  if (props.orderId) {
    getSaleOrderById(props.orderId)
  }
})

function individualDetails(row) {
  let ids
  if (row.groupConcatIds) {
    //未定义表示没有分组条件
    ids = row.groupConcatIds
  } else {
    ids = '' + row.id
  }
  console.log(row, 'row')
  individualInfo.query = {
    id: {
      queryType: 'IN',
      queryCategory: 'AND',
      value: ids,
    },
    orderId: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: props.orderId,
    },
  }
  individualInfo.info = row
  individualInfo.visible = true
}

function getSaleOrderById(orderId) {
  tableInfo.refresh = Math.random()
  detailPurchReturn(orderId).then((resp) => {
    if (resp && resp.success) {
      infoList.data = resp.data
    }
  })
}
function makeSure() {
  const ids = [infoList.data.id]
  if (ids.length) {
    saleReturnConfirm(ids).then((res) => {
      if (res) {
        emit('callback', true)
      }
    })
  }
}
function reject() {
  const ids = [infoList.data.id]
  if (ids.length) {
    saleReturnReject(ids).then((res) => {
      if (res) {
        emit('callback', true)
      }
    })
  }
}
function receive() {
  const ids = [infoList.data.id]
  if (ids.length) {
    saleReturnReceive(ids).then((res) => {
      if (res) {
        emit('callback', true)
      }
    })
  }
}
function refuse() {
  const ids = [infoList.data.id]
  if (ids.length) {
    saleReturnRefuse(ids).then((res) => {
      if (res) {
        emit('callback', true)
      }
    })
  }
}
</script>
